<template>
  <div id="chart" style="width: 600px; height: 600px;"></div>
</template>

<script>
import { onMounted, onUnmounted, ref } from 'vue';
import { init, dispose } from 'klinecharts'

export default {
  name: 'KlineChartComponent',
  setup() {
    const chartRef = ref(null);
    let chart = null;
    let socket = null;

    const initChart = () => {
      chart = init('chart');
    };

    // const fetchHistoricalData = async () => {
    //   try {
    //     // 修正请求地址
    //     const response = await axios.get('http://localhost:8000/api/historical-data');
    //     applyNewData(chart, response.data, false, () => {});
    //   } catch (error) {
    //     console.error('Failed to fetch historical data:', error);
    //   }
    // };

    const connectWebSocket = () => {

      // 修正 WebSocket 地址
      socket = new WebSocket('ws://localhost:8000/line-data');
      socket.onmessage = (event) => {
        const newData = JSON.parse(event.data);
        chart.applyNewData(newData)
        console.log(newData)
      };
      socket.onerror = (error) => {
        console.error('WebSocket error:', error);
      };
    };

    onMounted(() => {
      initChart();
      // fetchHistoricalData();
      connectWebSocket();
    });

    onUnmounted(() => {
      dispose('chart');
      if (socket) {
        socket.close();
      }
    });

    return {
      chartRef
    };
  }
};
</script>
